<script lang="ts" setup>
import { login, logout } from '@/api/user';
import { setToken } from '@/utils/auth';
import type { FormInstance, FormRules } from 'element-plus';

interface RuleForm {
	username: string;
	password: string;
}

const ruleFormRef = ref<FormInstance>();
const form = reactive<RuleForm>({
	username: '',
	password: '',
});
const rules = reactive<FormRules<RuleForm>>({
	username: [
		{ required: true, message: '请输入用户名', trigger: 'blur' },
		{ min: 2, max: 12, message: '用户名长度必须为2~12位', trigger: 'blur' },
	],
	password: [
		{ required: true, message: '请输入密码', trigger: 'blur' },
		{ min: 8, max: 18, message: '密码长度必须为8~18位', trigger: 'blur' },
	],
});

async function submitForm(formEl: FormInstance | undefined) {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			const { username, password } = form;
			login({ username, password }).then(res => {
				setToken(res.token);
			});
		} else {
			console.log('error submit!', fields);
		}
	});
}

function resetForm(formEl: FormInstance | undefined) {
	if (!formEl) return;
	formEl.resetFields();
}
async function logoutFn() {
	const res = await logout();
	console.log(res);
}
</script>

<template>
	<div class="page page-login w-full h-full">
		<div class="form">
			<p class="w-auto text-3xl text-center mb-16">登录</p>
			<el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px">
				<el-form-item label="username" prop="username">
					<el-input v-model="form.username" />
				</el-form-item>
				<el-form-item label="password" prop="password">
					<el-input v-model="form.password" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submitForm(ruleFormRef)">Create</el-button>
					<el-button @click="resetForm(ruleFormRef)">Reset</el-button>
				</el-form-item>
			</el-form>
			<el-button @click="logoutFn">退出登录</el-button>
		</div>
	</div>
</template>

<style lang="scss">
.page.page-login {
	position: relative;
	background: url('@img/common/login-bg.jpg') no-repeat;
	background-size: cover;

	.form {
		position: absolute;
		inset: 0;
		margin: auto;
		max-width: 750px;
		min-width: 550px;
		width: 60%;
		height: 400px;
		padding-top: 36px;
		padding-left: 36px;
		padding-right: 52px;
		transition: 200ms linear;
		background: rgb(228 237 250 / 10%);
		background-size: cover;
		backdrop-filter: saturate(180%) blur(5px);
	}
}
</style>
